<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>4.ajax_post.html</title>

    <style>
        #content{
            width: 300px;
            height: 200px;
            background: aquamarine;
        }
    </style>
</head>
<body>
<div id="content">

</div>
<button id="btn">发送</button>
<script>
    let content =document.getElementById("content");
    let btn =document.getElementById("btn");
    
    btn.onclick =()=>{
      const xmlHttpRequest = new XMLHttpRequest();
      xmlHttpRequest.onreadystatechange =()=>{
         if (xmlHttpRequest.readyState === 4){
             if( xmlHttpRequest.status >=200 && xmlHttpRequest.status<300){
                 content.innerHTML =`<h1>${xmlHttpRequest.response}</h1>`
             }
         }
      }

           xmlHttpRequest.open("POST","./ajax_post");

           //使用urlencoded的方式发送数据
           /* xmlHttpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded")
           xmlHttpRequest.send('username=lily&age=21');*/

          //使用json的方式发送数据
           xmlHttpRequest.setRequestHeader("Content-type","application/json");
           const jsonData ={
               username: "Alice",
               age:12,
               score: 100
           }
           //get请求参数直接使用URL拼接
           //post请求参数在send()方法内发送
           xmlHttpRequest.send(JSON.stringify(jsonData));

    }
</script>
</body>
</html>